package com.ebt.m.utils.android;

import android.util.Base64;
import android.util.Log;

import com.ebt.m.commons.utils.MD5Util;
import com.ebt.m.data.entity.FileTypeBean;
import com.ebt.m.data.middle.Security;
import com.ebt.m.exception.EBTException.EBTSoapHeaderException;
import com.ebt.m.utils.ConfigData;
import com.ebt.m.utils.android.ProductDownloader.OnDownloadCallBack;
import com.ebt.m.utils.fileutils.FileUtils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.Map;

/**
 * SingleDownloaderThread 主要功能：<br>
 * 1 获取下载文件的大小<br>
 * 2 下载整个文件<br>
 * 3 保存下载的文件<br>
 *
 * @author ZhanWu.Li
 * @create 2013.12.28
 */
public class SingleDownloaderThread extends DonwloadThread {
    private final String TAG = "SingleDownloaderThread";

    private boolean isFinish;

    private int mDownLength;

    private long needDownSize;

    private boolean paused;

    private boolean canceled = false;
    private boolean isThreadComplete = false;

    private int startPos;
    private FileTypeBean mFileType;
    private RandomAccessFile outputStream;
    private String mfilePath;
    private File tempFile;
    private String mStrURL;
    private String mCompanyId;
    private String mProductId;

    private boolean soapHeaderIsvalidate;

    private OnDownloadCallBack callBack;

    public SingleDownloaderThread(FileTypeBean fileType, String filePath, String compId, String productId) {
        mFileType = fileType;
        mProductId = productId;
        mCompanyId = compId;
        paused = false;
        isFinish = false;
        mfilePath = filePath;
        mDownLength = 0;
        startPos = 0;
        soapHeaderIsvalidate = false;
    }

    @Override
    public void run() {
        if (!canceled) {
            isThreadComplete = false;
            downloadResource();
        }

    }

    /**
     * 下载资源
     */
    public void downloadResource() {
        /*
         * if(ConfigData.DEBUG){ Log.e(TAG, mFileType.getStrUrl() +
		 * " downloadFile start"); }
		 */
        isFinish = false;
        String wsdl = "";
        String soapAction = "";
        String method = "";
        String xmlns = "";
        Map paramsMap = new HashMap();
        // 定义待请求的URL
        // 设置需要传递的参数
        if (DownloaderConstants.STR_FILE_TYPE_JOSN.equals(mFileType.getFileType())) {
            paramsMap.put("id", "" + mProductId);

            wsdl = DownloaderConstants.URL_DOWNLOADWEBSERVICE_DAT_WSDL;
            soapAction = DownloaderConstants.URL_DOWNLOADWEBSERVICE_JSON_ACTION;
            xmlns = DownloaderConstants.URL_DOWNLOADWEBSERVICE_JSON_XMLNS;
            method = DownloaderConstants.URL_DOWNLOADWEBSERVICE_JSON_METHOD;
        } else {
            wsdl = DownloaderConstants.URL_DOWNLOADWEBSERVICE_RES_WSDL;
            // wsdl = DownloaderConstants.URL_LOCAL_DOWNLOADWEBSERVICE_DAT_WSDL;
            soapAction = DownloaderConstants.URL_DOWNLOADWEBSERVICE_FILE_ACTION;
            xmlns = DownloaderConstants.URL_DOWNLOADWEBSERVICE_FILE_XMLNS;
            method = DownloaderConstants.URL_DOWNLOADWEBSERVICE_FILE_METHOD;
            if (!DownloaderConstants.STR_FILE_TYPE_COMPANY_INTERPRETATION.equals(mFileType.getStrUrl())) {
                mStrURL = Security.AESEncrypt(mFileType.getStrUrl(), DownloaderConstants.AES_RESOURCE_ENCRYPT_KEY_4_WS);
            } else {
                mStrURL = mFileType.getStrUrl();
            }

            paramsMap.put("url", mStrURL);
        }
        if (ConfigData.DEBUG) {
            Log.i(TAG, "资源文件初始url is :" + mStrURL);
        }
        try {
            // 设置URL编码
            // String result = soapObject.sendRequest();
//			String result = WebServiceRequestHelper.sendRequest(paramsMap, wsdl, soapAction, method, xmlns);
            String result = WebServiceRequestHelper.sendRequestByNoAccount(paramsMap, wsdl, soapAction, method, xmlns);
            byte[] buffer = Base64.decode(result.getBytes(), Base64.DEFAULT);
            needDownSize = buffer.length;
            InputStream inputStream = new ByteArrayInputStream(buffer);
            createDownTempFile();

            Log.i("download", "----> 保存路径： " + tempFile.getPath());

            outputStream = new RandomAccessFile(tempFile, "rw");
            outputStream.setLength(0);
            outputStream.seek(mDownLength);
            int read = 0;
            byte[] buf = new byte[1024 * 50];
            while (false == isFinish && false == canceled) {
                while (true == paused) {
                    Thread.sleep(100);
                }
                read = inputStream.read(buf);
                if (read == -1) {
                    break;
                }
                outputStream.write(buf, 0, read);
                mDownLength = mDownLength + read;
                if (mDownLength == needDownSize + startPos) {
                    isFinish = true;
                    break;
                }
            }
            // Thread.sleep(50);

			/*
             * boolean isWriterDone=false; while (false==isWriterDone&& false ==
			 * canceled) {
			 * 
			 * read = inputStream.read(buf); if (read == -1) { break; }
			 * outputStream.write(buf, 0, read); mDownLength = mDownLength +
			 * read; if (mDownLength == needDownSize ) { isWriterDone = true;
			 * break; } outputStream.write(buf, 0, read);
			 * 
			 * }
			 */
            outputStream.close();

            inputStream.close();
            /*
             * if(isDownloadFileMD5Same()){ isFinish=true; }else{ isFinish
			 * =false; }
			 */
            if (ConfigData.DEBUG) {
                Log.d(TAG, "资源文件下载完毕！" + mFileType.getStrUrl() + " needDownSize:" + needDownSize);
                // Log.d(TAG,"mStrURL 连接失败！" );
            }

        } catch (EBTSoapHeaderException e) {
            e.printStackTrace();
            if (ConfigData.DEBUG) {
                Log.d(TAG, "EBTSoapHeaderException :" + e.toString());
            }
            soapHeaderIsvalidate = true;

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            if (ConfigData.DEBUG) {
                Log.d(TAG, "mStrURL 连接失败！" + mFileType.getStrUrl());

                // Log.d(TAG,"mStrURL 连接失败！" );
            }

        } catch (Exception e) {
            e.printStackTrace();
            if (ConfigData.DEBUG) {
                Log.d(TAG, "mStrURL 连接失败！" + mFileType.getStrUrl());
                // Log.d(TAG,"mStrURL 连接失败！" );
            }

        } finally {
            isThreadComplete = true;
        }
        /* 取消下载，删除下载文件 */
        if (false == isFinish && true == canceled) {
            if (tempFile != null && tempFile.exists()) {
                FileUtils.deleteFile(tempFile);
            }
        }

        if (ConfigData.DEBUG) {
            if (!isFinish) {
                Log.e(TAG, "--------------mStrURL 文件下载未完成！" + mFileType.getStrUrl());
            }
            //
            // if(canceled){
            // Log.e(TAG,"--------------mStrURL 文件下载取消！" +mFileType.getStrUrl()
            // );
            // }
        }

    }

    /**
     * 创建临时下载文件
     *
     * @throws IOException
     */
    private void createDownTempFile() throws IOException {
        String fileName = null;
        String filePath = null;
        if (DownloaderConstants.STR_FILE_TYPE_COMPANY_INTERPRETATION.equals(mFileType.getFileType())) {
            fileName = mfilePath.substring(mfilePath.lastIndexOf('/') + 1);
            filePath = mfilePath.substring(0, mfilePath.lastIndexOf("/"));

//            if ("0".equals(mFileType.getIndex())) {
//                fileName = fileName + ".temp";
//            } else {
//                fileName = fileName + ".temp" + mFileType.getIndex();
//            }

        } else {
            fileName = mfilePath.substring(mfilePath.lastIndexOf('/') + 1);
            filePath = mfilePath.substring(0, mfilePath.lastIndexOf("/"));

            fileName = fileName + ".temp";

        }
        File fileDir = new File(filePath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
//        tempFile = new File(filePath, fileName);
//        final File to = new File(filePath, fileName + 1);
//        tempFile.renameTo(to);
//        to.delete();
//        tempFile = new File(filePath, fileName);
//        tempFile.createNewFile();

        tempFile = new File(filePath, fileName);
        if (tempFile.exists()) {
            tempFile.delete();
        }
        tempFile.createNewFile();
    }

    @Override
    public long getFileSize() {
        return startPos + needDownSize;
    }

    /**
     * 删除临时文件
     */
    @Override
    public void deleteTempFile() {
        if (tempFile != null && tempFile.exists()) {
            tempFile.delete();
        }
    }

    @Override
    public double getDownLength() {
        if (needDownSize > 0) {
            return mDownLength * 1.0 / needDownSize;
        } else {
            return 0;
        }
    }

    @Override
    public boolean isThreadComplete() {
        return isThreadComplete;
    }

    @Override
    public void cancel() {
        canceled = true;
        if (isThreadComplete == true) {

            if (tempFile != null && tempFile.exists()) {
                FileUtils.deleteFile(tempFile);
            }
        }
    }

    @Override
    public void pause() {
        paused = true;
    }

    @Override
    public void reStart() {
        paused = false;
    }

    @Override
    public boolean isFinish() {
        return isFinish;
    }

    public void setFinished(boolean isFinish) {
        this.isFinish = isFinish;
    }

    public String getTempFilePath() {
        return mfilePath + ".temp";
    }

    public OnDownloadCallBack getCallBack() {
        return callBack;
    }

    public void setCallBack(OnDownloadCallBack callBack) {
        this.callBack = callBack;
    }

    @Override
    public boolean isSoapHeaderInvalidate() {

        return soapHeaderIsvalidate;
    }

    @Override
    public boolean isDownloadFileMD5Same() throws Exception {
        String key = MD5Util.getFileMD5String(tempFile);
        return MD5Util.checkPassword(key, mFileType.getMd5Key());

    }

    public String getmStrURL() {
        return mStrURL;
    }

    public void setmStrURL(String mStrURL) {
        this.mStrURL = mStrURL;
    }

    public FileTypeBean getmFileType() {
        return mFileType;
    }

    public void setmFileType(FileTypeBean mFileType) {
        this.mFileType = mFileType;
    }
}
